<?php

namespace App\Service\Common;

use App\Enums\OpenShop\InvestmentPromotion\OrganizationManageEnum;
use App\Models\OpenShop\InvestmentPromotion\OpenShopOrganizationManageModel;
use App\Service\BaseService;

class CommonPermissionService extends BaseService
{
    /**
     * @param string $basePermissionUri
     * @return bool
     */
    public static function hasAllPermission(string $basePermissionUri): bool
    {
        $basePermissionUri   = strtolower($basePermissionUri);
        $userInfo            = request()->user();
        $userPermissionLists = collect($userInfo->permissions)->map(function($v){
            return strtolower($v);
        })->values()->toArray();
        // 判断是否拥有所有权限
        if (in_array($basePermissionUri , $userPermissionLists)) {
            return true;
        }
        return false;
    }

    /**
     * 根据用户iD获取组织类别以及省区权限列表
     *
     * @param int $userId
     * @return array
     */
    public static function getOrganizationRegion(int $userId): array
    {
        $allOrganizationManage = OpenShopOrganizationManageModel::allOrganizationManage();

        $isHeadOffice      = false;
        $provinceCodeLists = [];
        $allOrganizationManage->each(function (OpenShopOrganizationManageModel $organizationManageModel) use (
            &$isHeadOffice,
            $userId,
            & $provinceCodeLists
        ) {
            $operationUserIds = collect([]);
            if (isJson($organizationManageModel->operationAttacheUser)) {
                $operationUserIds = collect(json_decode($organizationManageModel->operationAttacheUser, true))
                    ->pluck("uid")->toArray();
            }
            array_push($operationUserIds, $organizationManageModel->operationUid);
            if (in_array($userId, $operationUserIds)) {
                if ($organizationManageModel->type == OrganizationManageEnum::TYPE_HEADQUARTERS) {
                    $isHeadOffice = true;
                }

                if ($organizationManageModel->regionRel) {
                    $provinceCodeLists = array_merge(
                        $provinceCodeLists,
                        $organizationManageModel->regionRel->pluck("provinceCode")->toArray()
                    );
                }
            }
        });

        return [
            $isHeadOffice,
            array_unique($provinceCodeLists)
        ];
    }

}
